package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApCollectionService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author CC
 * time 2024-06-08
 * description
 */
@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {

    @Autowired
    private CacheService cacheService;

    /**
     * 文章收藏 / 不收藏
     * @param dto
     * @return
     */
    public ResponseResult collection(CollectionBehaviorDto dto) {
        if (dto==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocal.getUser();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        Short operation = dto.getOperation();
        String k = BehaviorConstants.USER_BEHAVIOR_COLLECTION+user.getId();
        String jsonData = (String) cacheService.hGet(k, user.getId().toString());
        if(StringUtils.isNotBlank(jsonData) && dto.getOperation() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"已收藏");
        }
        if (operation==0) {
            //收藏
//            ApCollection apCollection = new ApCollection();
//            apCollection.setCollection_time(new Date());
//            apCollection.setEntryId(user.getId());
//            apCollection.setPublish_time(dto.getPublishedTime());
//            apCollection.setType(dto.getType());
//            apCollection.setArticleId(dto.getEntryId());
//
//            baseMapper.insert(apCollection);
            cacheService.hPut(k,dto.getEntryId().toString(), JSON.toJSONString(dto));
        } else if (operation==1) {
            //删除
//            baseMapper.delete(Wrappers.lambdaQuery(ApCollection.class)
//                    .eq(ApCollection::getArticleId,dto.getEntryId()).eq(ApCollection::getEntryId,user.getId()));
            cacheService.hDelete(k,dto.getEntryId().toString());
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
